package org.batavi.login;

import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;


public class LoginAndLogoff {
	private WebDriver driver;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();
	@Before
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		baseUrl = "http://demo.batavi.org/admin/index.php?login";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Test
	public void testUntitled() throws Exception {
		goToAdminLoginPage();
		checkLoginHyperLink();
		enterAdminAccPass();
		logOff();
		//Check  that correct page is displayed
		assertTrue(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Dashboard[\\s\\S]*$"));
		//Logoff from BE
		driver.findElement(By.linkText("Logoff")).click();
		//Check successes message 
		assertTrue(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Success: You have been successfully logged out of this system\\.[\\s\\S]*$"));
	}

	public void logOff() {
		//Click Login button 
		driver.findElement(By.cssSelector("span.btn_r")).click();
	}

	public void enterAdminAccPass() {
		//Fill in Username: with Admin
		driver.findElement(By.id("admin_login_form_user_name")).sendKeys("demo");
		//Fill in Password: with 12345
		driver.findElement(By.id("admin_login_form_user_password")).sendKeys("demo");
	}

	public void checkLoginHyperLink() {
		//Check loggin hyperlink
		driver.findElement(By.linkText("Login")).click();
	}

	public void goToAdminLoginPage() {
		//Go to BE login page
		driver.get(baseUrl + "/admin/index.php?login");
	}

	@After
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}
}
